const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
// const TerserPlugin = require('terser-webpack-plugin');
// const MiniCssExtractPlugin = require('mini-css-extract-plugin')
// const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
const { merge } = require('webpack-merge')

const resolveApp = require('./paths')

const devConfig = require('./webpack.dev')
const prodConfig = require('./webpack.prod')
const commonConfig = {
  target: 'web',
  context: resolveApp('./'),
  entry: {
    index: '/src/index.js',
  },
  output: {
    filename: 'js/[name]-[chunkhash:6].js',
    path: resolveApp('./build'),
    publicPath: '/',
    chunkFilename: "js/[name].[contenthash:6].chunk.js" //name为optimization中的chunkIds
  },
  resolve: {
    extensions: [".js", ".json", ".jsx", ".ts", ".wasm", ".mjs"],
    mainFiles: ["main", "index"],
    alias: {
      "@": resolveApp("./src"),
    }
  },
  module: {
    strictExportPresence: true,
    rules: [
      {
        test: /\.(jpe?g|png|svg|gif)$/,
        type: 'asset',
        generator: {
          filename: 'res/img/[name]-[hash:6][ext]',
        },
        parser: {
          dataUrlCondition: {
            maxSize: 5 * 1024, // 14kb
          },
        },
        // use: [{
        //   loader: 'url-loader',
        //   options: {
        //     name: 'img/[name]-[hash:6].[ext]',
        //     // outputPath: 'img'
        //     limit: 6 * 1024
        //   }
        // }]
      },
      {
        test: /\.ttf|eot|woff2?/i,
        type: 'asset/resource',
        generator: {
          filename: 'res/font/[name]-[hash:6][ext]',
        },
      },
      {
        test: /\.jsx?$/i,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            // options: {
            //   presets: [
            //     ['@babel/preset-env', {
            //       // targets: [] //默认适配browerlist匹配的浏览器
            //     }],
            //     ['preset-react', {
            //       // targets: [] //默认适配browerlist匹配的浏览器
            //     }]
            //   ]
            // }
          },
          {
            loader: 'eslint-loader',
            // options: {
            //   emitError: false,
            //   emitWarning: false,
            //   failOnError: false,
            //   failOnWarning: false
            // }
          }
        ]
      },
      {
        test: /\.ts$/i,
        exclude: /node_modules/,
        use: [
          // { loader: 'babel-loader' },
          {
            loader: 'ts-loader',
            options: {
              silent: true
            }
          }
        ],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      //可配置将动态导入的chunk提前注入到html，由于暂不需要，未配置
      title: 'Webpack App',
      template: resolveApp('./public/index.html'),
    }),
    new webpack.DefinePlugin({
      BASE_URL: "'hpc'",
    }),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: resolveApp('./public'),
          globOptions: {
            ignore: ['**/index.html', '**/.DS_Store', '**/aa.txt'],
          },
        },
      ],
    }),
    // new FriendlyErrorsWebpackPlugin({
    //   compilationSuccessInfo: {
    //     messages: ['You application is running here http://localhost:8080']
    //   },
    //   clearConsole: false
    // })
    // 垫片，官方不推荐使用
    // new webpack.ProvidePlugin({
    //   // axios: "axios"
    //   axios: ["axios", "get"]
    // })
  ],
  stats: {
    preset: 'errors-warnings',
  },
  optimization: {
    // minimizer: [
    //   new TerserPlugin({
    //     parallel: true,
    //     extractComments: false
    //   }),
    // ],
    // chunkIds: "deterministic",
    splitChunks: {
      // async 异步
      // initial 同步
      // all 同异步
      chunks: "all",
      cacheGroups: {}
    },
    // runtimeChunk: true, multiple, single
    runtimeChunk: {
      // name: 'runtime-hpc'
      name: (entrypoint) => {
        return `async-${entrypoint.name}`
      }
    },
    //开发模式默认为true
    // sideEffects: true
  },
}

module.exports = function (env) {
  const isProduction = env.production

  process.env.NODE_ENV = isProduction ? "production" : "development"
  const config = isProduction ? prodConfig : devConfig
  return merge(commonConfig, config)
}
